// pages/detail/index.js
import { Topic } from "../../model/Topic";
import { Utils } from "../../utils/util.js";
import {User} from "../../model/User.js";
import { Comment } from "../../model/Comment.js";
import { Upload } from "../../model/Upload.js";
const topic = new Topic();
const utils = new Utils();
const comment = new Comment();
const upload = new Upload();
const user = new User();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        id: 0,
        detail: {},
        subCommentState: false,
        commentCon: "",
        commentConLength: 0,
        tempFilePaths: [],
        comments: [],
        cId: 0,
        upload: false,
        loadtype: "loading",
        intoViewId: 0,
        intoView: "",
        headPic: wx.getStorageSync("avatar"),
        placeHolder:"此时此刻我想说..."
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        if (options.cid) {
            this.setData({
                intoViewId: options.cid,
            });
        }
        this.setData({
            id: options.id
        });
        //请求帖子详情
        this._getDetail();
        //请求评论列表
        this._getCommentList({
            type: "first",
            postId: this.data.id
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        //请求帖子详情
        this._getDetail();
        //请求评论列表
        this._getCommentList({
            type: "first",
            postId: this.data.id
        });
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

        if (this.data.loadtype != "end") {
            this.setData({
                upload: true,
                loadtype: "loading"
            });
            this._getCommentList({
                type: "more",
                postId: this.data.id
            });
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    },
    /**
     *跳回首页
     */
    gotoHome() {
        wx.switchTab({
            url: '/pages/index/index',
        })
    },
    /**
     * 请求详情
     */
    _getDetail() {
        topic.getDetail(this.data.id)
            .then(res => {
                const nowDate = new Date();
                res.data.CreateTime = utils.timestampFormat(res.data.CreateTime);
                res.data.imgArr = res.data.Images == "" ? [] : res.data.Images.split(",");
                res.data.videoArr = res.data.Videos == "" ? [] : res.data.Videos.split(",");
                if (res.data.CategoryId == 2) {
                    res.data.isExpire = res.data.VoteExpire < nowDate;
                    res.data.VoteExpire = res.data.VoteExpire.substring(0, 10);
                    res.data.votes = res.data.Vote.map((vote) => {
                        vote.checked = false;
                        return vote;
                    })
                }
                this.setData({
                    detail: res.data
                });
            })
            .catch(err => {
                wx.showToast({
                    title: err.msg,
                    icon: "none"
                })
            });
    },
    /**
     * 投票完成的回调
     */
    vote(e) {
        let { postId, voteId } = e.detail;
        let topic = this.data.detail;
        topic.LoggerCanVote = 0;
        topic.VoteNum = topic.VoteNum * 1 + voteId.length;
        topic.VoteUserNum = topic.VoteUserNum * 1 + 1;
        let votes = topic['Vote'];
        let newVotes = votes.map((vote) => {
            let RatioAnimation = wx.createAnimation({
                duration: 1500,
                timingFunction: "ease-out"
            });
            if (voteId.indexOf(vote.VoteId) >= 0) {
                vote.LoggerIsVote = 1;
                vote.VoteNum = vote.VoteNum * 1 + 1;
            }
            if (topic.VoteNum != 0) {
                vote.Ratio = Math.round(vote.VoteNum / topic.VoteNum * 100) + "%";
            }

            RatioAnimation.width(vote.Ratio).step();
            vote['animation'] = RatioAnimation.export();
            return vote;
        });
        topic.votes = newVotes;

        this.setData({
            detail: topic
        });
    },
    /**
     * 请求评论列表
     */
    _getCommentList(options) {
        if (options.type == "first") {
            this.setData({
                loadtype: "loading"
            });
        }
        comment.getComments(options)
            .then(res => {
                let comments = res.data.Results.map((comment) => {
                    comment.CreateTime = utils.timestampFormat(comment.CreateTime);
                    if (comment.Replies.length > 0) {
                        comment.Replies = comment.Replies.map((replay) => {
                            replay.CreateTime = utils.timestampFormat(replay.CreateTime);
                            return replay;
                        });
                    }
                    return comment;
                });
                if (options.type == "first") {
                    wx.stopPullDownRefresh();
                    this.setData({
                        comments: []
                    });
                    this.setData({
                        comments: comments,
                        upload: false
                    });
                    setTimeout(() => {
                        let newComments = comments.map((comment) => {
                            if (comment.CommentId == this.data.intoViewId) {
                                let iscomment = wx.createAnimation();
                                iscomment.backgroundColor("#FFFFCC").step({
                                    duration: 1000,
                                }).backgroundColor("#fff").step();
                                comment.iscomment = iscomment.export();
                            } else {
                                comment.iscomment = "";
                            }
                            return comment
                        });
                        this.setData({
                            comments: newComments,
                            intoView: `c${this.data.intoViewId}`
                        });
                    }, 500);
                } else {
                    this.setData({
                        comments: this.data.comments.concat(comments),
                        upload: false
                    })
                }

                if (res.data.TotalPage <= res.data.Page) {
                    this.setData({
                        upload: true,
                        loadtype: "end"
                    });
                }
            })
            .catch(err => {
                wx.showToast({
                    title: err.msg,
                    icon: "none"
                });
            });
    },
    loadMoreComment() {
        if (this.data.loadtype != "end") {
            this.setData({
                upload: true,
                loadtype: "loading"
            });
            this._getCommentList({
                type: "more",
                postId: this.data.id
            });
        }
    },
    /**
     * 点赞、取消点赞
     */
    thumb() {
        const ty = this.data.detail['LoggerIsLike'] == "N" ? "like" : "unlike"
        let options = {
            type: ty,
            id: this.data.id
        }
        topic.like(options)
            .then(res => {
                if (options.type == "like") {
                    this.setData({
                        ['detail.LoggerIsLike']: "Y",
                        ['detail.LikeNum']: this.data.detail.LikeNum * 1 + 1
                    });
                } else {
                    this.setData({
                        ['detail.LoggerIsLike']: "N",
                        ['detail.LikeNum']: this.data.detail.LikeNum * 1 - 1
                    });
                }

            })
            .catch(err => {
                wx.showToast({
                    title: err.msg,
                    icon: "none"
                })
            });
    },
    /**
     * 关注、取关
     */
    follow() {
        const ty = this.data.detail['LoggerIsFollow'] == "N" ? "follow" : "unfollow";
        let options = {
            type: ty,
            id: this.data.id
        }
        topic.follow(options)
            .then(res => {
                if (options.type == "follow") {
                    this.setData({
                        ['detail.LoggerIsFollow']: "Y",
                        ['detail.FollowNum']: this.data.detail.FollowNum * 1 + 1
                    });
                } else {
                    this.setData({
                        ['detail.LoggerIsFollow']: "N",
                        ['detail.FollowNum']: this.data.detail.FollowNum * 1 - 1
                    });
                }

            })
            .catch(err => {
                wx.showToast({
                    title: err.msg,
                    icon: "none"
                })
            });
    },
    /**
     * 预览图片
     */
    previewImg(e) {
        const index = e.currentTarget.dataset.index;
        utils.previewImage(index, this.data.detail['imgArr']);
    },
    /**
     * 视频播放
     */
    playVideo(e) {
        const url = e.currentTarget.dataset.url;
        wx.navigateTo({
            url: `/pages/video/index?url=${url}`
        });
    },
    /**
     * 点击评论框
     */
    gotoComm(e) {
        if (e.detail.cid) {
            this.setData({
                cId: e.detail.cid,
                placeHolder:`@${e.detail.nick}`
            });
        } else {
            this.setData({
                cId: 0,
                placeHolder:"此时此刻我想说..."
            });
        }
        this.setData({
            subCommentState: true
        });
    },
    hiddenComment() {
        this.setData({
            subCommentState: false,
            commentCon: "",
            commentConLength: 0
        });
    },
    /**
     * 绑定输入
     */
    bindInputComment(e) {
        let content = e.detail.value.replace(/\s+/g, "").replace(/[\r\n]/g, "");
        this.setData({
            commentCon: content,
            commentConLength: content.length
        });
    },
    /**
     * 上传图片
     */
    uploadPic() {
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: (result) => {
                let files = result.tempFilePaths.map(file => {
                    let objfile = {};
                    objfile.type = 1;
                    objfile.url = file;
                    return objfile;
                });
                this.setData({
                    sourceType: 1,
                    tempFilePaths: files
                });
            },
            fail: (err) => {
                if (err.errMsg === "chooseImage:fail cancel") {
                    wx.showToast({
                        title: '取消选择',
                        icon: "none"
                    })
                } else {
                    wx.showToast({
                        title: '微信接口调用失败',
                        icon: "none"
                    })
                }
            }
        });
    },
    /**
     * 上传视频
     */
    uploadVideo() {
        wx.chooseVideo({
            sourceType: ['album', 'camera'],
            compressed: true,
            maxDuration: 20,
            success: (res) => {
                if (res.duration > 20) {
                    wx.lin.showDialog({
                        type: "alert",
                        title: "提示",
                        content: "视频长度不能大于20s",
                        success: (res) => {}
                    })
                    return false;
                }
                let objfile = {
                    type: 2,
                    url: res.tempFilePath,
                }
                this.setData({
                    sourceType: 2,
                    tempFilePaths: [objfile]
                });
            },
            fail: (err) => {
                if (err.errMsg === "chooseImage:fail cancel") {
                    wx.showToast({
                        title: '取消选择',
                        icon: "none"
                    })
                } else {
                    wx.showToast({
                        title: '微信接口调用失败',
                        icon: "none"
                    })
                }
            }
        });
    },
    /**
     * 删除所选的资源
     */
    delPic(e) {
        this.setData({
            tempFilePaths: []
        });
    },
    /**
     * 发布评论
     */
    subComment() {
        if (this.data.commentCon == "" && this.data.tempFilePaths.length == 0) {
            wx.showToast({
                title: '请输入评论内容',
                icon: "none"
            })
            return false;
        }
        let options = {};
        if (this.data.cId == 0) {
            options = {
                postId: this.data.id,
                content: this.data.commentCon,
                image: "",
                video: ""
            }
        } else {
            options = {
                commentId: this.data.cId,
                content: this.data.commentCon,
                image: "",
                video: ""
            }
        }
        if (this.data.tempFilePaths.length > 0) {
            upload.upload(this.data.tempFilePaths)
                .then(res => {
                    let fileUrls = [];
                    res.forEach((file) => {
                        let fileData = JSON.parse(file.data);
                        fileUrls.push(fileData.data.url);
                    });
                    if (this.data.sourceType == 1) {
                        options.image = fileUrls.join(',');
                    } else {
                        options.video = fileUrls.join(',');
                    }
                    if (this.data.cId == 0) {
                        this._publish(options);
                    } else {
                        this._replay(options);
                    }

                })
                .catch(err => {
                    wx.showToast({
                        title: err.msg,
                        icon: "none"
                    });
                });
        } else {
            if (this.data.cId == 0) {
                this._publish(options);
            } else {
                this._replay(options);
            }
        }
    },
    /**
     * 执行发布
     */
    _publish(options) {
        comment.comment(options)
            .then(res => {
                wx.showToast({
                    title: '提交成功',
                });
                setTimeout(() => {
                    this.setData({
                        subCommentState: false,
                        tempFilePaths: [],
                        commentCon: "",
                        commentConLength: 0
                    })
                    this._getCommentList({
                        type: "first",
                        postId: this.data.id
                    });
                });
            })
            .catch(err => {
                wx.showToast({
                    title: err.msg,
                    icon: "none"
                })
            });
    },
    /**
     * 执行回复
     */
    _replay(options) {
        comment.reply(options)
            .then(res => {
                wx.showToast({
                    title: '提交成功',
                });
                setTimeout(() => {
                    this.setData({
                        subCommentState: false,
                        tempFilePaths: [],
                        commentCon: "",
                        commentConLength: 0
                    })
                    this._getCommentList({
                        type: "first",
                        postId: this.data.id
                    });
                });
            })
            .catch(err => {
                wx.showToast({
                    title: err.msg,
                    icon: "none"
                });
            });
    },
    /**
     * 刷新评论
     */
    reloadcomment() {
        this._getCommentList({
            type: "first",
            postId: this.data.id
        });
    },
    /**
     * 举报
     */
    report() {
        let itemList = ["恶意引战", "劣质广告", "日经贴, 重复太多", "拒绝黄赌毒", "包含政治敏感信息", "其他理由"];
        let PostId = this.data.detail.PostId;
        wx.showActionSheet({
            itemList: itemList,
            success: function(e) {
                let options = {
                    id: PostId,
                    type: 1,
                    reason: e.tapIndex + 1
                }
                user.report(options)
                    .then(res => {
                        wx.showToast({
                            title: '举报成功',
                        })
                    })
                    .catch(err => {
                        wx.showToast({
                            title: err.msg,
                            icon: "none"
                        })
                    });
            }
        })
    }
})